package com.xintonghua.bussiness.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.design.widget.TabLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xintonghua.bussiness.BuildConfig;
import com.xintonghua.bussiness.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import me.iwf.photopicker.PhotoPicker;

import static com.xcoder.lib.app.AppPathManager.DeleteFile;


/**
 * 作者：wanxianyi
 * 时间：2018/1/20.
 * 包名：com.xintonghua.meirang.utils
 */

public class MyUtils {
    /**
     * 设置tabLayout
     *
     * @param context
     * @param tab
     * @param left
     * @param right
     */
    public static void setTabLine(Context context, TabLayout tab, int left, int right) {
        try {
            Class<?> tablayout = tab.getClass();
            Field tabStrip = tablayout.getDeclaredField("mTabStrip");
            tabStrip.setAccessible(true);
            LinearLayout ll_tab = (LinearLayout) tabStrip.get(tab);
            for (int i = 0; i < ll_tab.getChildCount(); i++) {
                View child = ll_tab.getChildAt(i);
                child.setPadding(0, 0, 0, 0);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
                //修改两个tab的间距
                params.setMarginStart(MyUtils.dip2px(context, left));
                params.setMarginEnd(MyUtils.dip2px(context, right));
                child.setLayoutParams(params);
                child.invalidate();
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * dip转换成px
     *
     * @return dip转换的px
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 判断集合是否为null或者0个元素
     *
     * @param c
     * @return
     */
    public static boolean isNullOrEmpty(Collection c) {
        if (null == c || c.isEmpty()) {
            return true;
        }
        return false;
    }

    /**
     * 获取屏幕宽度
     */
    public static int getWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getWidth();
    }

    /**
     * 隐藏软键盘
     *
     * @param activity
     */
    public static void hideSoftInput(Activity activity) {
        View view = activity.getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 检测网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo[] allNetworkInfo = connectivityManager.getAllNetworkInfo();
            if (allNetworkInfo != null) {
                for (NetworkInfo networkInfo : allNetworkInfo) {
                    if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 保存sp的信息
     *
     * @param context 配置
     * @param spName  名称
     * @param params  需要设置的参数
     * @return 保存是否成功
     */
    public static boolean saveSp(Context context, String spName, Map<String, String> params) {
        SharedPreferences sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        for (String s : params.keySet()) {
            editor.putString(s, params.get(s));
        }

        return editor.commit();
    }


    public static boolean saveSp(Context context, String spName, String key, String value) {
        SharedPreferences sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        editor.putString(key, value);

        return editor.commit();
    }


    /**
     * 获取sp保存的信息
     *
     * @param context 配置
     * @param spName  名称
     * @param key     需要获取的key
     * @return 获取的内容
     */
    public static String getSp(Context context, String spName, String key) {
        SharedPreferences sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
        return sp.getString(key, "");
    }

    /**
     * Toast提示
     *
     * @param resId
     */
    public static void mToast(Context context, int resId) {
        Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
    }

    public static void mToast(Context context, String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 倒计时类
     *
     * @param btVerify
     * @return
     */
    public static CountDownTimer getTimeCount(final TextView btVerify) {
        class TimeCount extends CountDownTimer {
            public TimeCount(long millisInFuture, long countDownInterval) {
                super(millisInFuture, countDownInterval);
            }

            @Override
            public void onFinish() {
                btVerify.setText("重新获取");
                btVerify.setEnabled(true);
            }

            @Override
            public void onTick(long millisUntilFinished) {
                String text = millisUntilFinished / 1000 + "s";
                btVerify.setText(text);
                btVerify.setEnabled(false);
            }
        }
        return new TimeCount(60 * 1000, 1000);
    }


    public static String getMoney(Context context, double money) {
        return String.format(context.getString(R.string.money), new BigDecimal(money).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
    }

    public static String getMoneys(Context context, double money) {
        return String.format(context.getString(R.string.moneys), new BigDecimal(money).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
    }


    /**
     * 通过类名启动Activity，并且含有Bundle数据
     *
     * @param pBundle
     */
    public static void openActivity(Context context, Class<?> pClass, Bundle pBundle) {
        Intent intent = new Intent(context, pClass);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        context.startActivity(intent);
    }

    public static void openActivity(Context context, Class<?> pClass, Parcelable data) {
        Intent intent = new Intent(context, pClass);
        Bundle bundle = new Bundle();
        bundle.putParcelable(BuildConfig.FLAVOR, data);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }


    /**
     * 通过类名启动Activity
     *
     * @param pClass
     */
    public static void openActivity(Context context, Class<?> pClass) {
        openActivity(context, pClass, new Bundle());
    }


    /**
     * 获取拼接字符串
     *
     * @param list
     * @return
     */
    public static String getStringSplitValue(List<String> list) {
        StringBuilder builder = new StringBuilder();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                if (i == list.size() - 1) {
                    builder.append(list.get(i));
                } else {
                    builder.append(list.get(i) + ",");
                }
            }
        }
        return builder.toString();
    }

    /**
     * 将用逗号分隔开的数值转为数组
     *
     * @param value
     * @return
     */
    public static List<String> getListStringSplitValue(String value) {
        if (!TextUtils.isEmpty(value)) {
            String[] list = value.split(",");
            return Arrays.asList(list);
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 弹出软键盘
     *
     * @param editText
     * @param activity
     */
    public static void showSoftInput(EditText editText, Activity activity) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, 0);
    }

    /**
     * 启动拨打电话
     *
     * @param context     必须要
     * @param phoneNumber
     */
    public static void startCall(Context context, String phoneNumber) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_CALL);//指定意图动作
        intent.setData(Uri.parse("tel:" + phoneNumber));//指定电话号码
        context.startActivity(intent);
    }

    public static void saveVideoBitmap(Context mContext, String bitName, Bitmap mBitmap) {
        File f = new File(mContext.getFilesDir().getAbsolutePath() + "/meirang" + bitName);
        try {
            f.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查activity是否已经关闭
     *
     * @param mActivity 需要检查的activity
     * @return 结果
     */
    public static boolean activityIsFinished(Activity mActivity) {
        if (mActivity == null || mActivity.isFinishing()) {
            return true;
        }
        return false;
    }

    /**
     * 开启照片选择页面
     *
     * @param activity
     * @param count
     * @param requestCode
     */
    public static void startPhotoPicker(Activity activity, int count, int requestCode) {
        PhotoPicker.builder()
                .setPhotoCount(count)
                .setShowCamera(true)
                .setShowGif(false)
                .setPreviewEnabled(false)
                .start(activity, requestCode);
    }

    public static final String DEFAULT_PAHT_ROOT = Environment.getExternalStorageDirectory().getAbsolutePath() + "/wxy/";
    /**
     * 记录通知文件
     */
    public static final String DEFAULT_FILE_CACHE_PATH = DEFAULT_PAHT_ROOT + "file/";
    /**
     * 图片存放路径
     */
    public static final String DEFUALT_IMAGE_SAVE_PATH = DEFAULT_PAHT_ROOT + "Images/";


    public static File getImagePath() {
        File file = new File(DEFUALT_IMAGE_SAVE_PATH);
        if (createFolder(file)) {
            return file;
        } else if (!file.exists()) {
            if (!file.mkdirs()) {
                File file1 = new File(DEFAULT_PAHT_ROOT);
                if (file1.exists()) {
                    DeleteFile(file1);
                }
                DeleteFile(file);
            }
            File file1 = new File(DEFUALT_IMAGE_SAVE_PATH);
            if (createFolder(file1)) {
                return file;
            }
        }
        return null;
    }

    /**
     * 创建文件夹
     *
     * @param folder folderPath
     * @throws IOException
     */
    public static boolean createFolder(File folder) {
        if (!isSDCardMounted()) {
            return false;
        }
        if (!folder.exists()) {
            return folder.mkdirs();
        }
        return true;
    }

    /**
     * sdcard是否挂载
     */
    public static boolean isSDCardMounted() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }


}
